﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Thread thread = new Thread(new ThreadStart(Listen));
            thread.Start();
        }

        public void Listen()
        {
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");
            int port = 2112;
            TcpListener tcpListener = new TcpListener(localAddr, port);
            tcpListener.Start();
            try
            {
                while (true)
                {
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();

                    NetworkStream ns = tcpClient.GetStream();

                    Action<string> showMethod = (x) => UpdateDispaly(x);

                    StreamReader sr = new StreamReader(ns);
                    string result = sr.ReadToEnd();
                    Invoke(showMethod, new object[] { result });
                    tcpClient.Close();
                }
            }
            catch (Exception e)
            {
                label1.Text = e.Message;
            }
            finally
            {
                tcpListener.Stop();

            }
        }

        public void Hi()
        {

        }

        public void UpdateDispaly(string text)
        {
            this.label1.Text = text;
        }

        protected delegate void UpdateDisplayDeletegate(string text);

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}
